/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.rest.front;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.system.bo.req.QuestionAnswerReq;
import me.zhengjie.modules.system.bo.req.YplyReq;
import me.zhengjie.modules.system.domain.DccJifen;
import me.zhengjie.modules.system.domain.DccQuestionAnswer;
import me.zhengjie.modules.system.domain.DccUser;
import me.zhengjie.modules.system.service.*;
import me.zhengjie.modules.system.service.dto.*;
import me.zhengjie.modules.system.service.mapstruct.DccQuestionMapper;
import me.zhengjie.utils.RedisUtils;
import me.zhengjie.utils.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.hibernate.transform.Transformers;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @website https://eladmin.vip
* @author cjl
* @date 2023-05-16
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "DCC答题相关管理")
@RequestMapping("/front/question")
public class FrontQuestionController {



    private final DccQuestionAnswerService dccQuestionAnswerService;

    private final DccQuestionService dccQuestionService;
    private final DccUserService dccUserService;
    private final DccJifenService dccJifenService;
    private final RedisUtils redisUtils;
    private final EntityManager entityManager;

    public  Map<String, Object> listBySQL(String sql) {

        Query query = entityManager.createNativeQuery(sql);

        query.unwrap(org.hibernate.SQLQuery.class)
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

        List<Map<String, Object>> resultList = query.getResultList();
        return resultList.get(0);
    }

    /**
     * 注意数据权限的问题，数据库查的过程会筛选数据权限导致参数查询不生效
     * @param number
     * @return
     */
    @Log("题目列表")
    @ApiOperation("题目列表")
    @AnonymousAccess
    @GetMapping(value = "/list")
    public ResponseEntity<Object> queryDccYaopinlanyong(@RequestParam("param") String number){
        //判断是不是999，是999的话就是最后一关
        DccQuestionQueryCriteria criteria =new DccQuestionQueryCriteria();
        Object total=1;
        Map<String, Object> maps = listBySQL("select max(common_id) as commend,max(id) as id  from dcc_question group by common_id order by common_id desc limit 1");
        total=maps.get("commend");
        if (number.equals("999")){
            criteria.setCommonId(maps.get("commend").toString());
        }else{
            criteria.setCommonId(number);
        }
        Sort sort =Sort.by(Sort.Direction.ASC,"recommend");
        Pageable pageable =PageRequest.of(0, 100,sort);
        Map<String, Object> stringObjectMap = dccQuestionService.queryAll(criteria, pageable);
        List<DccQuestionDto> content = (List<DccQuestionDto>) stringObjectMap.get("content");
        List<DccQuestionDto> collect = content.stream().filter(e -> e.getCommonId().equals(number)).collect(Collectors.toList());
        stringObjectMap.put("content",collect);
        stringObjectMap.put("totalQuestion",total);
        return new ResponseEntity<>(stringObjectMap,HttpStatus.OK);
    }

    @Log("当前客户第几关")
    @ApiOperation("当前客户第几关")
    @AnonymousAccess
    @GetMapping(value = "/getNum")
    public ResponseEntity<Object> getNum(){
        if (!StpUtil.isLogin()){
            return new ResponseEntity<>(null,HttpStatus.UNAUTHORIZED);
        }

        DccQuestionAnswerQueryCriteria criteria =new DccQuestionAnswerQueryCriteria();
        criteria.setUid(StpUtil.getLoginIdAsString());
        Map map=new HashMap();

           Sort.Order order = new Sort.Order(Sort.Direction.DESC,"operator");
           Sort.Order order1 = new Sort.Order(Sort.Direction.DESC,"id");
            //如果有多个排序条件 建议使用此种方式 使用 Sort.by 替换之前的  new Sort();
            Sort sort = Sort.by(order,order1);

        //根据id排序获取最大的id
        Pageable pageable =PageRequest.of(0, 1,sort);
        Map<String, Object> stringObjectMap = dccQuestionAnswerService.queryAll(criteria, pageable);
        List<DccQuestionAnswerDto> content = (List<DccQuestionAnswerDto>) stringObjectMap.get("content");
        //查看当前数据是否是本次目录的最后一个，是的话
        Integer operator=1;
        if(CollectionUtils.isEmpty(content)){
            map.put("guanshu",operator);
            Map<String, Object> maps = listBySQL("select max(commid) as commend,max(id) as id  from dcc_question group by commid order by commid desc limit 1");
            map.put("totalQuestion",maps.get("commend"));
            return new ResponseEntity<>(map,HttpStatus.OK);
        }
        Object o = redisUtils.get("answer" + StpUtil.getLoginIdAsString());
        if (ObjectUtil.isAllNotEmpty(o)){
            operator=Integer.parseInt(o.toString());
        }

        Object o1 = redisUtils.get("end:" + StpUtil.getLoginIdAsString());
        if (ObjectUtil.isAllNotEmpty(o1)){
            operator=999;
            Object o2 = redisUtils.get("endTotal:"+StpUtil.getLoginIdAsString());
            if (ObjectUtil.isAllNotEmpty(o2)){
                operator=999999;
            }
        }
        map.put("guanshu",operator);
        Map<String, Object> maps = listBySQL("select max(commid) as commend,max(id) as id  from dcc_question group by commid order by commid desc limit 1");
        map.put("totalQuestion",maps.get("commend"));
        return new ResponseEntity<>(map,HttpStatus.OK);
    }

    //todo 没有处理分数相关的，最好交前端处理实在不行后端处理
    @Log("答题")
    @ApiOperation("答题")
    @AnonymousAccess
    @PostMapping(value = "/answer")
    public ResponseEntity<Object> answer(@RequestBody QuestionAnswerReq yplyReq){
        if (!StpUtil.isLogin()){
            return new ResponseEntity<>(null,HttpStatus.UNAUTHORIZED);
        }
        DccQuestionAnswer dccQuestionAnswer=new DccQuestionAnswer();
        dccQuestionAnswer.setAnswer(yplyReq.getAnswer());
        dccQuestionAnswer.setType(yplyReq.getType().toString());
        dccQuestionAnswer.setQuestionId(yplyReq.getQuestionId());
        dccQuestionAnswer.setQuestionName(yplyReq.getQuestionName());
        dccQuestionAnswer.setUid(StpUtil.getLoginId().toString());
        dccQuestionAnswer.setStatus(yplyReq.getStatus());
        dccQuestionAnswer.setCreatedAt(new Timestamp(System.currentTimeMillis()));
        dccQuestionAnswer.setOperator(yplyReq.getCommonNum());
        dccQuestionAnswer.setCode(yplyReq.getScore());
        dccQuestionAnswer.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
        DccQuestionAnswerDto dccQuestionAnswerDto = dccQuestionAnswerService.create(dccQuestionAnswer);
        Integer guanshu=1;
        if (yplyReq.getIsEnd()!=null&&yplyReq.getIsEnd()){
            guanshu=Integer.parseInt(yplyReq.getCommonNum())+1;
            redisUtils.set("answer"+StpUtil.getLoginIdAsString(),guanshu);

            if (Integer.parseInt(yplyReq.getScore())>0){
                //积分上传记录
                DccJifen dccJifen=new DccJifen();
                dccJifen.setUid(StpUtil.getLoginIdAsString());
                dccJifen.setPoint(20);
                dccJifen.setCommonId(dccQuestionAnswerDto.getId());
                dccJifen.setText("答题闯关积分");
                dccJifen.setType(2);
                dccJifen.setStatus(1);
                dccJifen.setCreatedAt(new Timestamp(System.currentTimeMillis()));
                dccJifen.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
                dccJifenService.create(dccJifen);
                DccUserDto user = (DccUserDto) StpUtil.getSession().get("user");
                int i = Integer.parseInt(StringUtils.isEmpty(user.getGroupid())?"0":user.getGroupid()) + 20;
                user.setGroupid(i+"");

                StpUtil.getSession().set("user",user);
                DccUser dccUser=new DccUser();
                BeanUtil.copyProperties(user,dccUser);
                dccUser.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
                dccUserService.update(dccUser);
                //判断是否是最后一道题，如果是的话，就设置redis缓存，告诉客户已经答完了所有题目
                Map<String, Object> maps = listBySQL("select max(commid) as commend,max(id) as id  from dcc_question group by commid order by commid desc limit 1");

                if (maps!=null&&maps.containsKey("id")&&maps.containsKey("commend")){
                    String id = maps.get("id").toString();
                    String commend = maps.get("commend").toString();
                    if (commend.equals(guanshu.toString())){
                        redisUtils.set("end:"+StpUtil.getLoginIdAsString(),yplyReq.getQuestionId());
                    }
                    if (yplyReq.getQuestionId().equals(id)){
                        redisUtils.set("endTotal:"+StpUtil.getLoginIdAsString(),yplyReq.getQuestionId());
                    }
                }
            }


        }else{
            redisUtils.set("answer"+StpUtil.getLoginIdAsString(),yplyReq.getCommonNum());
        }


        return new ResponseEntity<>(dccQuestionAnswerDto,HttpStatus.CREATED);

    }
}